//
//  Untitled.swift
//  PLDownload
//
//  Created by bin hu on 2025/7/7.
//

import Foundation

/// 密钥管理系统
class KeyManager {
    static let shared = KeyManager()
    private var keyCache = [String: Data]()  // [keyURI: keyData]
    
    func getKey(for keyURI: String, completion: @escaping (Result<Data, Error>) -> Void) {
        if let cachedKey = keyCache[keyURI] {
            completion(.success(cachedKey))
            return
        }
        
        guard let url = URL(string: keyURI) else {
            completion(.failure(DownloadError.invalidKeyURI))
            return
        }
        
        URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
            guard let data = data, error == nil else {
                completion(.failure(error ?? DownloadError.keyDownloadFailed))
                return
            }
            
            self?.keyCache[keyURI] = data
            completion(.success(data))
        }.resume()
    }
}
